package com.example.task4.servlet;

import com.example.task4.dao.UserDao;
import com.example.task4.domain.User;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.MultipartConfig;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.*;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.util.UUID;

@WebServlet("/user")
@MultipartConfig(fileSizeThreshold = 1024 * 10, maxFileSize = 1024 * 1024 * 5) // 5MB
public class UserServlet extends HttpServlet {

    private final UserDao userDao = new UserDao();

@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    String action = req.getParameter("action");
    if ("register".equals(action)) {
        handleRegister(req, resp);
    } else if ("login".equals(action)) {
        handleLogin(req, resp);
    } else if ("logout".equals(action)) {
        handleLogout(req, resp);
    } else {
        resp.sendError(HttpServletResponse.SC_BAD_REQUEST);
    }
}

private void handleLogout(HttpServletRequest req, HttpServletResponse resp) throws IOException {

    HttpSession session = req.getSession(false);
    if (session != null) {
        session.invalidate();
    }
    resp.sendRedirect(req.getContextPath() + "/index.jsp");
}


    private void handleRegister(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setCharacterEncoding("UTF-8");
        resp.setContentType("text/html; charset=UTF-8");


        String username = req.getParameter("username");
        String password = req.getParameter("password");
        String email = req.getParameter("email");

        if (username == null || username.isBlank() || password == null || password.isBlank()) {
            req.setAttribute("msg", "用户名和密码不能为空");
            req.getRequestDispatcher("/register.jsp").forward(req, resp);
            return;
        }

        if (userDao.findByUsername(username) != null) {
            req.setAttribute("msg", "用户名已存在");
            req.getRequestDispatcher("/register.jsp").forward(req, resp);
            return;
        }

        Part avatarPart = req.getPart("avatar");
        String avatarRelative = null;
        if (avatarPart != null && avatarPart.getSize() > 0) {
            String uploads = req.getServletContext().getRealPath("/uploads/avatars");
            File uploadDir = new File(uploads);
            if (!uploadDir.exists()) uploadDir.mkdirs();
            String submitted = avatarPart.getSubmittedFileName();
            String ext = "";
            if (submitted != null && submitted.contains(".")) ext = submitted.substring(submitted.lastIndexOf('.'));
            String filename = UUID.randomUUID().toString() + ext;
            File saved = new File(uploadDir, filename);
            try (InputStream in = avatarPart.getInputStream()) {
                Files.copy(in, saved.toPath());
                avatarRelative = req.getContextPath() + "/uploads/avatars/" + filename;
            }
        }

        User user = new User(username, password, email, avatarRelative);
        boolean ok = userDao.save(user);
        if (ok) {
            // 自动登录并跳转主页
            HttpSession session = req.getSession();
            session.setAttribute("user", user);
            resp.sendRedirect(req.getContextPath() + "/home.jsp");
        } else {
            req.setAttribute("msg", "注册失败，请稍后重试");
            req.getRequestDispatcher("/register.jsp").forward(req, resp);
        }
    }

    private void handleLogin(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setCharacterEncoding("UTF-8");
resp.setContentType("text/html; charset=UTF-8");

        String username = req.getParameter("username");
        String password = req.getParameter("password");
        User u = userDao.findByUsernamePassword(username, password);
        if (u != null) {
            HttpSession session = req.getSession();
            session.setAttribute("user", u);
            resp.sendRedirect(req.getContextPath() + "/home.jsp");
        } else {
            req.setAttribute("msg", "用户名或密码错误");
            req.getRequestDispatcher("/login.jsp").forward(req, resp);
        }
    }
}
